import { FC, useState } from 'react';
import { Document, Page } from 'react-pdf';
import Image from '@/components/Image';
import ScrollModel from '@/components/ScrollModel';
import loadingIcon from '@/assets/loading_icon.png';
import styles from './style.less';

interface Iprops {
  fileUrl: string;
  width: number;
  height: number;
}
type textType = 'nodata' | 'filed' | 'loading';
const setText = (type: textType) => {
  switch (type) {
    case 'nodata':
      return <span>'文件不存在'</span>;
    case 'loading':
      return (
        <div className={styles.loading_content}>
          <Image src={loadingIcon} className={styles.loading_icon} />
          <span>文件加载中...</span>
        </div>
      );
    case 'filed':
      return <span>文件不存在或无法加载此文件</span>;
    default:
      return <span>预览发生未知错误</span>;
  }
};
const customElement = (type: textType, width: number, height: number) => {
  return (
    <div
      style={{
        width,
        height,
        boxSizing: 'border-box',
        padding: '20px',
        textAlign: 'center',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {setText(type)}
    </div>
  );
};
const PdfPreviewer: FC<Iprops> = (props) => {
  const { fileUrl = '', width, height } = props;

  const [total, setTotal] = useState<number>(0);
  const loadSuccess = ({ numPages }: any) => {
    setTotal(numPages);
  };

  const buildPages = (total: number) => {
    let arr: any[] = [];
    arr.length = total;
    arr.fill('pdf');
    return arr.map((item: any, index: number) => (
      <Page
        pageNumber={index + 1}
        key={`${item}-${index}`}
        className={styles.page_content}
      />
    ));
  };

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
      }}
    >
      <ScrollModel width={width} height={height}>
        <Document
          className={styles.pdf_container}
          file={{
            url: fileUrl,
          }}
          onLoadSuccess={loadSuccess}
          noData={customElement('nodata', width, height)}
          error={customElement('filed', width, height)}
          loading={customElement('loading', width, height)}
        >
          {buildPages(total)}
        </Document>
      </ScrollModel>
    </div>
  );
};
export default PdfPreviewer;
